package com.leilbase.mspring.web.handler;

import com.leilbase.mspring.web.mvc.Controller;
import com.leilbase.mspring.web.mvc.RequestMapping;
import com.leilbase.mspring.web.mvc.RequestParam;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MappingHandlerManager {

    public static List<MappingHandler> mappingHandlerList = new ArrayList<>();

    public static void resolveMappingHandler(List<Class<?>> classList) {
        classList.stream()
                .filter(cls->cls.isAnnotationPresent(Controller.class))
                .forEach(MappingHandlerManager::parseHandlerFromController);
    }

    private static void parseHandlerFromController(Class<?> cls) {
        // 获取类中的所有method
        Method[] methods = cls.getDeclaredMethods();
        Arrays.stream(methods)
                .filter(method -> method.isAnnotationPresent(RequestMapping.class))
                .forEach(method -> parseHandlerFromMethod(method, cls));
    }

    private static void parseHandlerFromMethod(Method method, Class<?> cls) {
        final String uri = method.getDeclaredAnnotation(RequestMapping.class).value();
        Parameter[] parameters = method.getParameters();
        List<String> paramNameList = Arrays.stream(parameters)
                .filter(parameter -> parameter.isAnnotationPresent(RequestParam.class))
                .map(parameter -> parameter.getDeclaredAnnotation(RequestParam.class).value())
                .collect(Collectors.toList());
        String[] paramNames = paramNameList.toArray(new String[paramNameList.size()]);
        MappingHandler mappingHandler = new MappingHandler(uri, method, cls, paramNames);
        MappingHandlerManager.mappingHandlerList.add(mappingHandler);
    }


}
